package server;

import common.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * 客户端连接管理
 */
public class ClientManager {
    private static final Logger logger = LogUtil.getLogger(ClientManager.class.getName());

    // 客户端映射表
    private final Map<String, ClientHandler> clients = new ConcurrentHashMap<>();

    public Map<String, ClientHandler> getClients() {
        return clients;
    }

    /**
     * 添加客户端
     */
    public void addClient(String clientId, ClientHandler client) {
        clients.put(clientId, client);
        logger.info("Client added: " + clientId);
    }

    /**
     * 移除客户端
     */
    public void removeClient(String clientId) {
        clients.remove(clientId);
        logger.info("Client removed: " + clientId);
    }

    /**
     * 获取客户端
     */
    public ClientHandler getClient(String clientId) {
        return clients.get(clientId);
    }

    /**
     * 获取客户端数量
     */
    public int getClientCount() {
        return clients.size();
    }

    /**
     * 检查心跳超时
     */
    public void checkHeartbeats() {
        List<String> timeoutClients = new ArrayList<>();

        // 找出超时的客户端
        for (Map.Entry<String, ClientHandler> entry : clients.entrySet()) {
            ClientHandler client = entry.getValue();
            if (client.isTimeout()) {
                timeoutClients.add(entry.getKey());
            }
        }

        // 关闭超时的客户端
        for (String clientId : timeoutClients) {
            ClientHandler client = clients.get(clientId);
            if (client != null) {
                logger.info("Client timeout: " + clientId);
                client.close();
            }
        }
    }

    /**
     * 关闭所有客户端连接
     */
    public void closeAll() {
        for (ClientHandler client : clients.values()) {
            client.close();
        }
        clients.clear();
    }
}
